package client.gui.utils;

import java.awt.Image;
import java.util.ArrayList;

public class AnimatedImage {
	
	private ArrayList<Frame> frames = new ArrayList<Frame>();
    private int frameIndex = 0;
    private long animTime = 0;
    private long totalDuration = 0;


    public AnimatedImage(long duration, Image ... images) {
    	for(Image image : images) {
    		frames.add(new Frame(image, duration));
    	}
    	totalDuration = duration * images.length;
    }


    public void addFrame(Image image, long duration)
    {
        totalDuration += duration;
        frames.add(new Frame(image, totalDuration));
    }


    public void update(long elapsedTime) {
        if (frames.size() > 1) {
            animTime += elapsedTime;
            if (animTime >= totalDuration) {
                animTime = animTime % totalDuration;
                frameIndex = 0;
            }
            while (animTime > frames.get(frameIndex).duration) {
                frameIndex++;
            }
        }
    }

    public Image getCurrentImage() {
        if (frames.size() < 1) {
            return null;
        } else {
            return frames.get(frameIndex).image;
        }	
    }

    private class Frame {

        private Image image;
        private long duration;

        public Frame(Image image, long endTime) {
            this.image = image;
            this.duration = endTime;
        }
    }

}
